/*
 * @Descripttion:
 * @Author: jhw
 * @Date: 2023-12-13 14:40:14
 * @LastEditors: jhw
 * @LastEditTime: 2023-12-13 15:26:54
 */
import { Directive, DirectiveBinding, createApp, h } from 'vue';
import { Loading } from '@element-plus/icons-vue';
// <el-icon class="is-loading"> <Loading /> </el-icon>
export default <Directive>{
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;

    if (typeof value !== 'function') {
      throw new Error('v-loading 指令的值必须为函数');
    } else {
      // 获取原始函数
      const originalFunc = value;

      el.addEventListener('click', async (...args: any[]) => {
        // 1. Disabled button
        el.setAttribute('disabled', 'disabled');
        el.classList.add('is-loading');
        const icon = document.createElement('el-icon');
        icon.classList.add('el-icon', 'is-loading');
        const loadingIconVNode = h(Loading);
        createApp({
          render: () => loadingIconVNode,
        }).mount(icon);
        // Insert icon before text
        el.insertBefore(icon, el.childNodes[0]);
        // 2. Run original function
        try {
          await originalFunc(...args);
        } finally {
          // 3. Enable button
          el.removeAttribute('disabled');
          el.classList.remove('is-loading');
          el.removeChild(icon);
        }
      });
    }
  },
};
